package com.pdstudio.video;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pdstudio.bean.VideoSimpleInfo;
import com.pdstudio.weather.R;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class VideoMainActivity extends Activity implements
		OnCompletionListener, OnErrorListener, OnInfoListener,
		OnPreparedListener, OnSeekCompleteListener, OnVideoSizeChangedListener,
		SurfaceHolder.Callback {

	private LinearLayout loadLayout;
	private ListView listView;

	private List<VideoSimpleInfo> vss;
	public List<Map<String, Object>> meumList;// 存储图片
	public Map<String, Integer> fileMap;
	public Handler handler;

	// 下面的全是视频播放的变量
	private Display currentDisplay = null;
	private SurfaceView surfaceView = null;
	private SurfaceHolder surfaceHoler = null;
	private MediaPlayer mPlayer = null;
	private int videoWidth = 0, videoHeight = 0;
	private boolean readyToPlay = false;
	private static final String TAG = "-----VideoPlayer----";
	private MediaPlayer media = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.video_main);

		if (true) {// TODO 这里判断天气情况
			LinearLayout layout = (LinearLayout) findViewById(R.id.video_main);
			layout.setBackground(getResources().getDrawable(R.drawable.bgsun));
		}

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case 0: // 0列表数据加载完成
				{
					if (msg.obj != null) {
						vss = (List<VideoSimpleInfo>) msg.obj;
						initialImages();
					}
				}
					break;
				case 1: {
					listView.setAdapter(new VideoViewAdapter(
							getApplicationContext(), vss, false));
					loadLayout.setVisibility(View.GONE);

					// 播放视频
					playMedia("http://113.247.234.237/uploads/Files/000/000/001/108/-18235266093785.mp4");
				}
					break;
				default:
					break;
				}
			}
		};

		initial();
	}

	private void initial() {

		loadLayout = (LinearLayout) findViewById(R.id.file_refresh_panel);
		listView = (ListView) findViewById(R.id.vediocorner_listview);
		listView.setDivider(getResources().getDrawable(
				R.drawable.learningcorner_file_detail_content_divider_bg));
		listView.setDividerHeight(2);

		initialMedia();// 要先把media的控件初始化

		meumList = new ArrayList<Map<String, Object>>();
		fileMap = new HashMap<String, Integer>();

		// 首先获取视频列表信息
		new Thread(new Runnable() {
			@Override
			public void run() {
				List<VideoSimpleInfo> vsis = new ArrayList<VideoSimpleInfo>();
				SimpleDateFormat df = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");// 设置日期格式
				String[] path = new String[] {
						"http://113.247.234.237/uploads/Avatars/000/003/280/3280.jpg-small.jpg",
						"http://113.247.234.237/uploads/Avatars/000/003/280/3280.jpg-small.jpg",
						"http://113.247.234.237/uploads/Avatars/000/003/280/3280.jpg-small.jpg",
						"http://113.247.234.237/uploads/Avatars/000/003/280/3280.jpg-small.jpg",
						"http://113.247.234.237/uploads/Avatars/000/003/280/3280.jpg-small.jpg" };
				for (int i = 0; i < path.length; i++) {
					VideoSimpleInfo s = new VideoSimpleInfo();
					s.title = i + "";
					s.createTime = df.format(new Date());// new Date()为获取当前系统时间
					s.desc = i + "十八大精神介绍打了款剪短发";
					s.iamgeUrl = path[i];
					vsis.add(s);
				}
				Message m = new Message();
				m.what = 0;// 0表示列表数据加载完
				m.obj = vsis;
				handler.sendMessage(m);
			}
		}).start();
	}

	private void initialImages() {
		if (vss != null && vss.size() > 0) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					for (int i = 0; i < vss.size(); i++) {
						Map<String, Object> map = new HashMap<String, Object>();
						Map<String, Object> bitmap = send(
								getApplicationContext(), vss.get(i).iamgeUrl);
						if (map != null) {
							map.put("img", (Bitmap) (bitmap.get("img")));
							map.put("name", vss.get(i).iamgeUrl);
							meumList.add(map);
						}
						fileMap.put(vss.get(i).iamgeUrl,
								(Integer) (bitmap.get("length")));
					}
					handler.sendEmptyMessage(1);// 1表示图片加载完
				}
			}).start();

		}
	}

	private void initialMedia() {
		// SurfaceView设置
		surfaceView = (SurfaceView) findViewById(R.id.videoSurfaceView);
		surfaceHoler = surfaceView.getHolder();
		surfaceHoler.addCallback(this);
		surfaceHoler.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		// MediaPlayer设置
		mPlayer = new MediaPlayer();
		mPlayer.setOnCompletionListener(this);
		mPlayer.setOnErrorListener(this);
		mPlayer.setOnInfoListener(this);
		mPlayer.setOnPreparedListener(this);
		mPlayer.setOnSeekCompleteListener(this);
		mPlayer.setOnVideoSizeChangedListener(this);
		// 播放歌曲路径
		// Intent intent = getIntent();
		// address=intent.getStringExtra("ADDRESS");
		String address = "http://113.247.234.237/uploads/Files/000/000/001/108/-18235266093785.mp4";
		if (address == null || "".equals(address)) {
			Toast.makeText(this, "没有获取到视频网络地址", Toast.LENGTH_SHORT).show();
		} else {
			try {
				mPlayer.setDataSource(address);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		currentDisplay = getWindowManager().getDefaultDisplay();
	}

	private void playMedia(String address) {

		if (address == null || "".equals(address)) {
			Toast.makeText(this, "没有获取到视频网络地址", Toast.LENGTH_SHORT).show();
		} else {
			try {
				mPlayer.reset();
				mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				mPlayer.setDataSource(address);
				mPlayer.prepare();
				mPlayer.start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private Map<String, Object> send(Context context, String path) {
		Map<String, Object> map = new HashMap<String, Object>();
		ImageView imageView = null;
		imageView = new ImageView(context);
		// imageView.setMaxHeight(100);
		// imageView.setMaxWidth(100);
		Bitmap bitmap = null;
		try {
			URL url = new URL(path);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setConnectTimeout(5000);
			if (httpURLConnection.getResponseCode() == 200) {
				if (bitmap != null) {
					System.out.println("---" + bitmap);
					bitmap.recycle();
					System.gc();
				}
				InputStream is = httpURLConnection.getInputStream();
				bitmap = BitmapFactory.decodeStream(is);
				// BitmapFactory.Options options = new BitmapFactory.Options();
				// options.inSampleSize = computeSampleSize(options, -1,
				// 128*128);
				// options.inJustDecodeBounds = true;
				int length = httpURLConnection.getContentLength();
				// System.out.println(httpURLConnection.get);
				// MediaStore
				map.put("img", bitmap);
				map.put("length", length);
			} else {
				Toast.makeText(context, "服务器端响应错误", Toast.LENGTH_LONG).show();
			}
			httpURLConnection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;

	}

	@Override
	protected void onPause() {
		if (mPlayer.isPlaying())
			mPlayer.pause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		if (mPlayer.isPlaying())
			mPlayer.pause();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if (mPlayer.isPlaying())
			mPlayer.stop();
		mPlayer.release();
		mPlayer = null;
		super.onDestroy();
	}

	/*
	 * 视频列表的适配器
	 */
	public class VideoViewAdapter extends BaseAdapter {

		private List<VideoSimpleInfo> list;
		private Context context;

		private LayoutInflater li;
		private boolean isOpen;

		public VideoViewAdapter(Context context, List<VideoSimpleInfo> list,
				boolean isOpen) {
			this.context = context;
			this.list = list;
			li = LayoutInflater.from(context);
			this.isOpen = isOpen;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			// if(view==null){
			view = li.inflate(R.layout.video_main_item, null);
			// }

			final VideoSimpleInfo entity = list.get(position);
			view.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					/*
					 * 让视频换一个播放源
					 */
					// Intent i=new
					// Intent(VideoMainActivity.this,TestVideoActivity.class);
					// startActivity(i);
					playMedia("http://113.247.234.237/uploads/Files/000/000/001/047/17808971253856.mp4");
				}
			});
			TextView category_title = (TextView) view
					.findViewById(R.id.file_title);

			category_title.setText(entity.title);

			TextView file_time = (TextView) view.findViewById(R.id.file_time);
			file_time.setText(entity.createTime);

			TextView file_des = (TextView) view.findViewById(R.id.file_desc);
			file_des.setText("简介：" + entity.desc);

			ImageView img = (ImageView) view.findViewById(R.id.file_type_img);
			Map<String, Object> map = meumList.get(position);
			img.setImageBitmap((Bitmap) map.get("img"));
			return view;
		}

		public void setData(List<VideoSimpleInfo> dataList) {
			//
			this.list = dataList;

		}

	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	// create方法进行准备
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Log.v(TAG, "surfaceCreated method is called!!");
		mPlayer.setDisplay(holder);
		/*
		 * try { mPlayer.prepare(); } catch (IOException e) {
		 * e.printStackTrace(); //finish(); }
		 */
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
	}

	@Override
	public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
	}

	@Override
	public void onSeekComplete(MediaPlayer mp) {
	}

	// 播放处理
	@Override
	public void onPrepared(MediaPlayer mp) {
		// 全屏播放
		// videoHeight = currentDisplay.getHeight();
		// videoWidth = currentDisplay.getWidth();
		// 按视频本身大小播放
		videoWidth = mPlayer.getVideoWidth();
		videoHeight = mPlayer.getVideoHeight();
		// 在此可以根据情况进行缩放播放设置
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				videoWidth, videoHeight);
		// 居中
		lp.gravity = Gravity.CENTER_HORIZONTAL;
		surfaceView.setLayoutParams(lp);
		// mPlayer.start();
	}

	// Info 信息处理
	@Override
	public boolean onInfo(MediaPlayer mp, int what, int extra) {
		Log.v(TAG, "onInfo method is called!!");
		if (what == MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING) {
			Log.v(TAG, "Media Info, Media Info Bad Interleaving " + extra);
		} else if (what == MediaPlayer.MEDIA_INFO_NOT_SEEKABLE) {
			Log.v(TAG, "Media Info, Media Info Not Seekable " + extra);
		} else if (what == MediaPlayer.MEDIA_INFO_UNKNOWN) {
			Log.v(TAG, "Media Info, Media Info Unknown " + extra);
		} else if (what == MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING) {
			Log.v(TAG, "MediaInfo, Media Info Video Track Lagging " + extra);
		} else if (what == MediaPlayer.MEDIA_INFO_METADATA_UPDATE) {
			Log.v(TAG, "MediaInfo, Media Info Metadata Update " + extra);
		}
		return false;
	}

	// Error信息处理
	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		Log.v(TAG, "onError method is called!!");
		if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
			Log.v(TAG, "Media Error,Server Died" + extra);
		} else if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
			Log.v(TAG, "Media Error,Error Unknown" + extra);
		}
		return false;
	}

	// 播放完毕后,finish
	@Override
	public void onCompletion(MediaPlayer mp) {
		Log.v(TAG, "onCompletion method is called!!");
		finish();
	}

}
